﻿#include "RectEditEntry.h"
#include "IntegerEditEntry.h"
#include <QPointer>

struct RectEditEntry::RectEditEntryPrivate {
    QPointer<IntegerEditEntry> entryX;
    QPointer<IntegerEditEntry> entryY;
    QPointer<IntegerEditEntry> entryWidth;
    QPointer<IntegerEditEntry> entryHeight;
};

RectEditEntry::~RectEditEntry() { }

RectEditEntry::RectEditEntry(QWidget *parent) : StringEditEntry{parent} {
    p.reset(new RectEditEntryPrivate);
    initUi();
}

void RectEditEntry::setValue(const QRect &rect) {
    const auto text = QString("[(%1,%2),%3x%4]")
                          .arg(rect.x())
                          .arg(rect.y())
                          .arg(rect.width())
                          .arg(rect.height());
    StringEditEntry::setValue(text);

    p->entryX->setValue(rect.x());
    appendChildEntry(p->entryX);

    p->entryY->setValue(rect.y());
    appendChildEntry(p->entryY);

    p->entryWidth->setValue(rect.width());
    appendChildEntry(p->entryWidth);

    p->entryHeight->setValue(rect.height());
    appendChildEntry(p->entryWidth);
}

QRect RectEditEntry::value() const {
    QRect rct;
    rct.setX(p->entryX->value());
    rct.setX(p->entryY->value());
    rct.setX(p->entryWidth->value());
    rct.setX(p->entryHeight->value());
    return rct;
}

void RectEditEntry::onChildEntryValueChanged() {
    emit valueChanged(value());
}

void RectEditEntry::initUi() {
    p->entryX = new IntegerEditEntry;
    appendChildEntry(p->entryX);
    p->entryX->setRange(-QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
    connect(p->entryX, &IntegerEditEntry::valueChanged, this, &RectEditEntry::onChildEntryValueChanged);

    p->entryY = new IntegerEditEntry;
    appendChildEntry(p->entryY);
    p->entryY->setRange(-QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
    connect(p->entryY, &IntegerEditEntry::valueChanged, this, &RectEditEntry::onChildEntryValueChanged);

    p->entryWidth = new IntegerEditEntry;
    appendChildEntry(p->entryWidth);
    p->entryWidth->setRange(0, QWIDGETSIZE_MAX);
    connect(p->entryWidth, &IntegerEditEntry::valueChanged, this, &RectEditEntry::onChildEntryValueChanged);

    p->entryHeight = new IntegerEditEntry;
    appendChildEntry(p->entryHeight);
    p->entryHeight->setRange(0, QWIDGETSIZE_MAX);
    connect(p->entryHeight, &IntegerEditEntry::valueChanged, this, &RectEditEntry::onChildEntryValueChanged);

    retranslateUi();
}

void RectEditEntry::retranslateUi() {
    p->entryX->setTitle(tr("X"));
    p->entryY->setTitle(tr("Y"));
    p->entryWidth->setTitle(tr("Width"));
    p->entryHeight->setTitle(tr("Height"));
}
